<template>
  <div class="category-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <h1>分类管理</h1>
      <el-button type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon>
        添加分类
      </el-button>
    </div>

    <!-- 分类列表表格 -->
    <el-card class="category-table-card">
      <el-table :data="categoryList" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="categoryName" label="分类名称" />
        <el-table-column prop="categoryAlias" label="分类别名" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="showEditDialog(row.id)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="400px"
      @close="resetForm"
    >
      <el-form ref="categoryFormRef" :model="categoryForm" :rules="formRules" label-width="100px">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="categoryForm.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类别名" prop="categoryAlias">
          <el-input v-model="categoryForm.categoryAlias" placeholder="请输入分类别名" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue'
import { ElButton, ElTable, ElTableColumn, ElDialog, ElForm, ElFormItem, ElInput, ElMessageBox, ElMessage, ElIcon, ElEmpty, ElCard } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
// 导入配置好的axios实例
import request from '../utils/request'

export default {
  name: 'Category',
  components: {
    ElButton,
    ElTable,
    ElTableColumn,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElEmpty,
    ElCard,
    ElIcon,
    Plus
  },
  setup() {
    // 分类列表数据
    const categoryList = ref([])
    // 对话框显示状态
    const dialogVisible = ref(false)
    // 对话框标题
    const dialogTitle = ref('')
    // 当前操作类型（add或edit）
    const operationType = ref('')
    // 当前编辑的分类ID
    const currentEditId = ref(null)
    // 表单数据
    const categoryForm = reactive({
      categoryName: '',
      categoryAlias: ''
    })
    // 表单验证规则
    const formRules = reactive({
      categoryName: [
        { required: true, message: '请输入分类名称', trigger: 'blur' },
        { min: 2, max: 10, message: '分类名称长度在 2 到 10 个字符', trigger: 'blur' }
      ],
      categoryAlias: [
        { required: true, message: '请输入分类别名', trigger: 'blur' },
        { min: 2, max: 20, message: '分类别名长度在 2 到 20 个字符', trigger: 'blur' }
      ]
    })
    // 表单引用
    const categoryFormRef = ref(null)

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    // 获取分类列表
    const getCategoryList = async () => {
      try {
        const res = await request.get('/category/list')
        console.log('分类列表响应:', res)
        
        // 增强的响应数据处理逻辑
        // 1. 检查响应是否有效
        if (!res) {
          ElMessage.warning('响应数据为空')
          categoryList.value = []
          return
        }
        
        // 2. 检查是否有data字段，如果有就使用
        if (res.data !== undefined) {
          categoryList.value = res.data || []
        } else {
          // 3. 如果没有data字段，尝试直接使用res
          if (Array.isArray(res)) {
            categoryList.value = res
          } else {
            // 4. 否则显示空列表
            ElMessage.warning('响应数据格式不符合预期')
            categoryList.value = []
          }
        }
      } catch (error) {
        console.error('获取分类列表失败:', error)
        ElMessage.error('获取分类列表失败')
        categoryList.value = []
      }
    }

    // 显示添加分类对话框
    const showAddDialog = () => {
      operationType.value = 'add'
      dialogTitle.value = '添加分类'
      resetForm()
      dialogVisible.value = true
    }

    // 显示编辑分类对话框
    const showEditDialog = async (id) => {
      try {
        const res = await request.get(`/category/detail?id=${id}`)
        if (res.code === 0) {
          operationType.value = 'edit'
          dialogTitle.value = '编辑分类'
          currentEditId.value = id
          categoryForm.categoryName = res.data.categoryName
          categoryForm.categoryAlias = res.data.categoryAlias
          dialogVisible.value = true
        } else {
          ElMessage.error('获取分类详情失败：' + res.message)
        }
      } catch (error) {
        ElMessage.error('获取分类详情失败')
        console.error('获取分类详情失败:', error)
      }
    }

    // 重置表单
    const resetForm = () => {
      if (categoryFormRef.value) {
        categoryFormRef.value.resetFields()
      }
      categoryForm.categoryName = ''
      categoryForm.categoryAlias = ''
      currentEditId.value = null
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!categoryFormRef.value) return
      try {
        await categoryFormRef.value.validate()
        if (operationType.value === 'add') {
          await handleAdd()
        } else {
          await handleUpdate()
        }
      } catch (error) {
        return
      }
    }

    // 添加分类
    const handleAdd = async () => {
      try {
        const res = await request.post('/category/add', {
          categoryName: categoryForm.categoryName,
          categoryAlias: categoryForm.categoryAlias
        })
        if (res.code === 0) {
          ElMessage.success('添加分类成功')
          dialogVisible.value = false
          getCategoryList()
        } else {
          ElMessage.error('添加分类失败：' + res.message)
        }
      } catch (error) {
        ElMessage.error('添加分类失败')
        console.error('添加分类失败:', error)
      }
    }

    // 更新分类
    const handleUpdate = async () => {
      try {
        const res = await request.put('/category/update', {
          id: currentEditId.value,
          categoryName: categoryForm.categoryName,
          categoryAlias: categoryForm.categoryAlias
        })
        if (res.code === 0) {
          ElMessage.success('更新分类成功')
          dialogVisible.value = false
          getCategoryList()
        } else {
          ElMessage.error('更新分类失败：' + res.message)
        }
      } catch (error) {
        ElMessage.error('更新分类失败')
        console.error('更新分类失败:', error)
      }
    }

    // 删除分类
    const handleDelete = async (id) => {
      try {
        const confirmResult = await ElMessageBox.confirm(
          '确定要删除该分类吗？',
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        if (confirmResult === 'confirm') {
          const res = await request.delete(`/category/del?id=${id}`)
          if (res.code === 0) {
            ElMessage.success('删除分类成功')
            getCategoryList()
          } else {
            ElMessage.error('删除分类失败：' + res.message)
          }
        }
      } catch (error) {
        if (error === 'cancel') return
        ElMessage.error('删除分类失败')
        console.error('删除分类失败:', error)
      }
    }

    // 页面加载时获取分类列表
    onMounted(() => {
      getCategoryList()
    })

    return {
      categoryList,
      dialogVisible,
      dialogTitle,
      categoryForm,
      formRules,
      categoryFormRef,
      formatDate,
      showAddDialog,
      showEditDialog,
      resetForm,
      handleSubmit,
      handleDelete
    }
  }
}
</script>

<style scoped>
.category-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.category-table-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table__header th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa !important;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989;
  border-color: #f78989;
}
</style>